﻿using ImageProcessor;
using ImageProcessor.Imaging.Formats;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using RestSharp;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
using System.Xml;

namespace heyirunde.wx
{
    /// <summary>
    /// picturetest 的摘要说明
    /// </summary>
    public class picturetest : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            string imagePath = "";
            try
            {
                imagePath = Draw(CreateTempQRCode("ASDFGH"), "http://thirdwx.qlogo.cn/mmopen/vi_32/vM2NmFZQYma9Mb32UMUicbJlBNtbrCYxmRmAicPMlFymUKD8Rib4nRGF2dc4fXicPZShcpHCTBqwXrYZCric9zXUPeg/132", "我是昵称");
            }catch(Exception ex)
            {
                context.Response.Write(ex);
                return;
            }
          

            RestClient client_upload = new RestClient("https://api.weixin.qq.com/cgi-bin/media/upload");
            RestRequest request_upload = new RestRequest(Method.POST);
           // request_upload.Method = Method.POST;
            request_upload.AddParameter("access_token", wxconfig.getToken());
            request_upload.AddParameter("type", "image");
            request_upload.AddParameter("media", "filename");

            request_upload.AddFile("file", imagePath);

            IRestResponse res = client_upload.Execute(request_upload);
            JObject oj_up = (JObject)JsonConvert.DeserializeObject(res.Content);

          

            string media_id = (string)oj_up["media_id"];
            if (!string.IsNullOrEmpty(media_id))
            {

                string resxml = "<xml><ToUserName><![CDATA[" + "oEhd9jgzaYI08aSuudnWSIX_hIN4" + "]]></ToUserName><FromUserName><![CDATA[" + "gh_e629bec2aa54" + "]]></FromUserName><CreateTime>" + "1589555576" + "</CreateTime><MsgType><![CDATA[image]]></MsgType><Image><MediaId><![CDATA[" + media_id + "]]></MediaId></Image></xml>";

                HttpContext.Current.Response.Write(resxml);
                HttpContext.Current.Response.End();
                /*
                XmlDocument xml_tui = new XmlDocument();

                xml_tui.LoadXml(resxml);


                if (!string.IsNullOrEmpty(resxml))
                {
                    HttpContext.Current.Response.Write(xml_tui);
                    HttpContext.Current.Response.End();
                }
                else
                {
                    HttpContext.Current.Response.Write("");
                    HttpContext.Current.Response.End();
                }
                */
                return;
            }
        }

        /// <summary>
        /// 获取临时二维码ticket  haibao_tui
        /// </summary>
        /// <param name="scene_str">场景值ID openid做场景值ID</param>
        /// <returns></returns>
        public static string CreateTempQRCode(string scene_str)
        {
            RestClient client = new RestClient("https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" + wxconfig.getToken());

            RestRequest request = new RestRequest();
            request.Method = Method.POST;
            request.AddJsonBody(new
            {
                action_name = "QR_LIMIT_STR_SCENE",
                action_info = new
                {
                    scene = new { scene_str = scene_str }
                }
            }
        );
            IRestResponse res = client.Execute(request);

            JObject jobect = (JObject)JsonConvert.DeserializeObject(res.Content);

            string ticket = (string)jobect["ticket"];

            if (string.IsNullOrEmpty(ticket))
            {

                return " ";
            }
            return ticket;
        }



        /// <summary>
        /// 生成带二维码的专属推广图片
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public string Draw(string ticket, string headimgurl, string nickname)
        {
            //背景图片
            string path = HttpContext.Current.Server.MapPath("/img/27.jpg");

            System.Drawing.Image imgSrc = System.Drawing.Image.FromFile(path);

            //处理二维码图片大小 240*240px
            System.Drawing.Image qrCodeImage = ReduceImage("https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=" + ticket, 240, 240);

            //处理头像图片大小 100*100px
            Image titleImage = ReduceImage(headimgurl, 200, 200);

            using (Graphics g = Graphics.FromImage(imgSrc))
            {
                //画专属推广二维码
                g.DrawImage(qrCodeImage, new Rectangle(imgSrc.Width- qrCodeImage.Width-30,
                imgSrc.Height - qrCodeImage.Height - 30,
                qrCodeImage.Width,
                qrCodeImage.Height),
                0, 0, qrCodeImage.Width, qrCodeImage.Height, GraphicsUnit.Pixel);

                //画头像
                g.DrawImage(titleImage, 30 , imgSrc.Height - qrCodeImage.Height, titleImage.Width, titleImage.Height);

                Font font = new Font("宋体", 40, FontStyle.Bold);

                g.DrawString(nickname, font, new SolidBrush(Color.Black), 20, imgSrc.Height - qrCodeImage.Height+ titleImage.Height+5);
            }
            string newpath = @"E:\HYRD\heyirunde\heyirunde\img\27new.jpg";
            ISupportedImageFormat format = new PngFormat { Quality = 70 };
            using (MemoryStream outStream = new MemoryStream())
            {
                // 使用重载初始化ImageFactory以保留EXIF元数据。
                using (ImageFactory imageFactory = new ImageFactory(true))
                {
                    // 加载，调整大小，设置格式和质量并保存图像。
                    imageFactory.Load(imgSrc)
                        .Format(format)
                        .Resize(new Size(540,1054))
                    
                        .Save(newpath);

                }
                /*

                  ImgManager img = new ImgManager()
                  {
                      userGuid = " ",
                      imgurl = path,
                      miniurl = newpath,
                      width = imgSrc.Width,
                      height = imgSrc.Height,
                      size = " ",
                      type = 1,
                      createTime = DateTime.Now,
                      isdel = 0
                  };
                  db.Insert(img);
                  */
            }

            //  imgSrc.Save(newpath, System.Drawing.Imaging.ImageFormat.Jpeg);
            return newpath;
        }


        /// <summary>
        /// 缩小/放大图片
        /// </summary>
        /// <param name="url">图片网络地址</param>
        /// <param name="toWidth">缩小/放大宽度</param>
        /// <param name="toHeight">缩小/放大高度</param>
        /// <returns></returns>
        public Image ReduceImage(string url, int toWidth, int toHeight)
        {
            WebRequest request = WebRequest.Create(url);
            WebResponse response = request.GetResponse();
            Stream responseStream = response.GetResponseStream();

            Image originalImage = Image.FromStream(responseStream);
            if (toWidth <= 0 && toHeight <= 0)
            {
                return originalImage;
            }
            else if (toWidth > 0 && toHeight > 0)
            {
                if (originalImage.Width < toWidth && originalImage.Height < toHeight)
                    return originalImage;
            }
            else if (toWidth <= 0 && toHeight > 0)
            {
                if (originalImage.Height < toHeight)
                    return originalImage;
                toWidth = originalImage.Width * toHeight / originalImage.Height;
            }
            else if (toHeight <= 0 && toWidth > 0)
            {
                if (originalImage.Width < toWidth)
                    return originalImage;
                toHeight = originalImage.Height * toWidth / originalImage.Width;
            }
            Image toBitmap = new Bitmap(toWidth, toHeight);
            using (Graphics g = Graphics.FromImage(toBitmap))
            {
                g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
                g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                g.Clear(Color.Transparent);
                g.DrawImage(originalImage,
                   new Rectangle(0, 0, toWidth, toHeight),
                   new Rectangle(0, 0, originalImage.Width, originalImage.Height),
                   GraphicsUnit.Pixel);
                originalImage.Dispose();
                return toBitmap;
            }
        }


        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}